package com.authine.cloudpivot.ext.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.sso.security.BaseAuthenticationToken;
import com.authine.cloudpivot.web.sso.template.BaseSimpleTemplate;
import com.authine.cloudpivot.web.sso.template.ResponseTypeEnum;
import com.authine.cloudpivot.web.sso.template.SimpleTemplateConfig;
import com.authine.cloudpivot.web.sso.view.ThreadLocalValue;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Created by osfhmy on 2020/11/17.
 */
@Component
@Slf4j
public class SsoSimpleTemplate extends BaseSimpleTemplate {

    @Autowired
    private DubboConfigService dubboConfigService;

    SsoSimpleTemplate() {
        super(SimpleTemplateConfig.builder()
            .requestMatcher(new AntPathRequestMatcher("/login/sso", HttpMethod.GET.name()))
            .responseType(ResponseTypeEnum.JSON)
            // 云枢OAuth2登录的ClientId 具体体现在base_security_client表中
            .redirectClientID("api").build());
    }

    /**
     * 获取建行组织的服务
     * 
     * @return OrganizationFacade
     */
    public OrganizationFacade getOrganizationFacade() {
        return dubboConfigService.getOrganizationFacade();
    }

    @Override
    public String getSourceId(BaseAuthenticationToken baseAuthenticationToken) {
        log.debug("========== code: {} ==========", baseAuthenticationToken.getCode());
        return baseAuthenticationToken.getCode();
    }

    @SuppressWarnings("deprecation")
    @Override
    public UserModel getUser(Object sourceId) {
        // 校验传入的参数信息，根据具体的场景匹配规则去查找用户
        log.debug("sourceId={}", sourceId);
        String[] strings = sourceId.toString().split(",");
        UserModel userModel;
        if (strings.length > 1) {
            log.debug("============ ThreadLocalValue corpId: {} ==========", strings[1]);
            ThreadLocalValue.localCorpId.set(strings[1]);
            userModel = getOrganizationFacade().getUserByUserIdAndCorpId(strings[0], strings[1]);
        } else {
            if (sourceId.toString().contains(",")) {
                log.debug("========== userId: {} =============",
                    sourceId.toString().substring(0, sourceId.toString().length() - 1));
                userModel = getOrganizationFacade()
                    .getUserByUserId(sourceId.toString().substring(0, sourceId.toString().length() - 1));
            } else {
                log.debug("========== userId: {} =============", strings[0]);
                userModel = getOrganizationFacade().getUserByUserId(strings[0]);
            }
        }
        if (null == userModel) {
            log.error("========== 单点登陆，在云枢中没有该用户的信息:{}。请确保引擎连接正常。==========", sourceId);
        } else {
            log.debug("单点登陆成功, 用户的信息:{}, {}, {}", sourceId, userModel.getUsername(), userModel.getName());
        }
        return userModel;
    }

}
